﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MyProfile : System.Web.UI.Page
{

    #region VARIABLES

    Service service;
    Validation validation;
    //UserCredentials userC;
     
    #endregion 
    Sanitize sanitize;
    
    #region PROPERTIES

    private UserCredentials User
    {
        get { return Session["User"] as UserCredentials; }
        set { Session["User"] = value; }
    }

    #endregion 


    #region BUTTON_ONCLICK METHODS

    protected void EditButton_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["Edit"] == "true")
        {
            validation = new Validation();
            
            string signature = "";
            if (SignatureTextBox.Text != null)
            {
                signature = SignatureTextBox.Text;
            }
            if (validation.ValidateProfileInfo(EmailTextBox.Text, signature))
            {
                string oldEmail = User.Email;
                string oldSignature = User.Signature;

                string sanitizedEmail = sanitize.EncodeText((EmailTextBox.Text));
                string sanitizedSignature = sanitize.EncodeText((SignatureTextBox.Text));
                //userC.UserID = User.UserID;
                User.Email = sanitizedEmail;
                User.Signature = sanitizedSignature;

                service.UpdateUserEmailAndSignatureOnUserID(User);


                LoggEntry loggEntry = new LoggEntry();
                loggEntry.Details = String.Format("User : {0} , Has changed their profile info from : email:{1}, signature : {2} To : Email:{3}, Signature:{4}", User.Username, oldEmail, oldSignature, User.Email, User.Signature);
                loggEntry.IP = Request.UserHostAddress;
                service.SaveLoggEntry(loggEntry);

                string  message = "Your Profile Has Been Updated";
                Session["successMessage"] = message;
                Response.Redirect("~/MyProfile.aspx");
            }
            else
            {
                DisplayAllErrorMessages();
            }
        }
        else
        {
            Response.Redirect("~/MyProfile.aspx?Edit=true");
        }
    }



    protected void ConfirmPasswordChangeButton_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["ChangePassword"] == "true")
        {
            validation = new Validation();
            Hashing hash = new Hashing();

            var oldPassword = OldPasswordTextBox.Text;
            var newPassword = NewPasswordTextBox.Text;

            if (validation.IsCorrectUsernameAndPassword(User.Username, oldPassword) &&
                validation.ComparePasswords(hash.HashPassword(oldPassword, User.Salt), User.Password))
            {                
                User.Salt = hash.GetRandomSalt();
                User.UserID = User.UserID;
                User.Password = hash.HashPassword(newPassword, User.Salt);


                LoggEntry loggEntry = new LoggEntry();
                loggEntry.Details = String.Format("User : {0} , Has changed their password", User.Username);
                loggEntry.IP = Request.UserHostAddress;
                service.SaveLoggEntry(loggEntry);

                service.UpdateUserPasswordOnUserID(User);                
                string message = ("Your Password Has Been Changed");
                Session["successMessage"] = message;
                Response.Redirect("~/MyProfile.aspx");
            }
            else
            {                
                DisplayAllErrorMessages();
            }
        }
    }

    #endregion 

    
    protected void Page_Load(object sender, EventArgs e)
    {
        sanitize = new Sanitize();
        service = new Service();
        if (!IsPostBack)
        {
            EmailTextBox.Text = User.Email;
            UsernameLabel.Text = User.Username;
            SignatureTextBox.Text = User.Signature;
        }
        if (Request.QueryString["Edit"] == "true")
        {
            EditProfile();
        }
        else if (Request.QueryString["ChangePassword"] == "true")
        {
            ChangePassword();
            EditEmailAndSignature.Visible = false;
        }
        else
        {
            ChangePasswordDiv.Visible = false;
        }        
    }

    private void EditProfile()
    {
        EmailTextBox.Enabled = true;
        ChangePasswordDiv.Visible = false;
        SignatureTextBox.Enabled = true;
        EditButton.CausesValidation = true;
        EditButton.ValidationGroup = "eval";
    }

    private void ChangePassword()
    {
        ChangePasswordDiv.Visible = true;
        OldPasswordTextBox.Enabled = true;
        NewPasswordTextBox.Enabled = true;
    }    

    private void DisplayAllErrorMessages()
    {
        List<string> errormessages = validation.GetErrorMessages();

        if (errormessages != null)
        {
            foreach (string error in errormessages)
            {
                AddErrorMessage(error);
            }
        }
    }

    #region  AddErrorMessage

    private void AddErrorMessage(string message)
    {
        Validators.Add(new CustomValidator
        {
            ErrorMessage = message,
            IsValid = false
        });
    }

    private void AddErrorMessage(IDataErrorInfo obj)
    {
        obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .Where(n => !String.IsNullOrWhiteSpace(obj[n])) // vill bara ha de som inte är tomma.
            .ToList()  // gör om till lista.
            .ForEach(n => AddErrorMessage(obj[n]));  // loopar igenom namnen som återstår o lägger till.
    }

    #endregion

}